package com.znsd.zl.app.user.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.google.gson.JsonObject;
import com.znsd.zl.app.user.annotation.Login;
import com.znsd.zl.app.user.entity.AppUserEntity;
import com.znsd.zl.app.user.utils.JwtUtils;
import com.znsd.zl.app.user.utils.RedisUtils;
import com.znsd.zl.exception.RRException;
import com.znsd.zl.utils.Constant;
import com.znsd.zl.utils.DateUtils;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.util.Date;

/**
 * <p>
 *      用户登录拦截器
 * </p>
 *
 * @ClassName AppUserLoginInterceptor
 * @Description 请求头中不存在token直接拦截
 * @Author jaypdd
 * @Date 2020/8/26 17:03
 * @Version v1.0
 */
@Component
public class AppUserLoginInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private JwtUtils jwtUtils;

	@Resource
	private RedisUtils redisUtils;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		Login annotation = null;
		// 判断当前接口是否存在login注解，存在继续执行
		if(handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		}
		// 注解未初始化直接放行
		if(annotation == null){
			return true;
		}

		String token = request.getHeader("token");
		// 判断用户是否携带token
		if ( token == null ) {
			throw new RRException("未登录", Constant.TOKEN_IS_NOT);
		}
		// 校验token是否过期
		String[] info = jwtUtils.tokenDecode(token);
		if ( info == null || !redisUtils.containsKey(info[0])) {
			throw new RRException("token 失效，请重新登录", Constant.TOKEN_IS_NOT);
		}

		return true;
	}

}
